import cloud from '@lafjs/cloud'
let dbName = "web-curriculum"
const db = cloud.database();
let data

export default async function (ctx: FunctionContext) {
  data = ctx.body.data
  switch (ctx.body.type) {
    case "add":
      return add()
      break;
    case "update":
      return update()
      break;
    case "del":
      return delFunc()
      break;
    default://不分页查询
      return Search()
      break;
  }
}

async function add() {
  await cloud.nw.db.add({
    dbName,
    dataJson: data,
    cancelAddTime: true
  });
  return cloud.utils.requestReturn({ data: "" })
}

async function delFunc() {
  await cloud.nw.db.del({
    dbName,
    whereJson: { _id: data._id }
  });
  return cloud.utils.requestReturn({ data: "" })
}

async function update() {
  let query = { ...data }
  delete query._id
  await cloud.nw.db.update({
    dbName,
    whereJson: {
      _id: data._id,
    },
    dataJson: query
  });
  return cloud.utils.requestReturn({ data: "" })
}

async function Search() {
  let { data } = await db.collection(dbName).get()
  return cloud.utils.requestReturn({ data })
}
